package com.duolaibei.business.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDexApplication;

import com.duolaibei.business.base.DlbIntentService;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.model.UserInfoData;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.log.LogDebug;
import com.duolaibei.business.view.goods.greendao.DaoMaster;
import com.duolaibei.business.view.goods.greendao.DaoSession;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.lang.reflect.Type;
import java.util.Stack;

/**
 * Created by xlm on 2017/10/27 0027
 */
public class App extends MultiDexApplication {

    public static MyHandler handler;
    private static Stack<Activity> mActivitys;
    private static App mApp;
    public MainActivity mainActivity;

    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        newActivityStack();
        //IntentService做初始化操作
        DlbIntentService.startInitService(mApp);
        if (handler == null) {
            handler = new MyHandler();
        }
        setDatabase();
    }
    /* 通过 DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的 SQLiteOpenHelper 对象。
可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为 greenDAO 已经帮你做了。
注意：默认的 DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。*/

    private void setDatabase() {
        mHelper = new DaoMaster.DevOpenHelper(this, "shangjia-db", null);
        db = mHelper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

    //static 代码段可以防止内存泄露
    static {
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            //设置全局的Header构建器
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            //设置全局的Footer构建器
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
    }


    /**
     * 获取application实例
     *
     * @return
     */
    public static App getApp() {
        return mApp;
    }

    /**
     * 结束所有activity
     */
    private void finishAllActivity() {
        while (!mActivitys.isEmpty()) {
            mActivitys.pop().finish();
        }
    }

    /**
     * 退出application
     */
    public void exitApplication(boolean needbackground) {
        finishAllActivity();
        if (!needbackground) {
            System.exit(0);
        }
    }

    /**
     * 注销
     */
    public void cancelAccount() {
        PreferenceUtil.setParam(Preferences.USERNAME, "");
        PreferenceUtil.setParam(Preferences.PASSWORD, "");
        setUserInfo(null);
    }

    private UserInfoData mUserInfo;

    /**
     * app登陆后，保存userInfo
     *
     * @param userInfo
     */
    public void setUserInfo(UserInfoData userInfo) {
        mUserInfo = userInfo;
        saveUserInfoToPrefrence(userInfo);
    }

    public UserInfoData getUserInfo() {
        if (mUserInfo == null) {
            mUserInfo = getUserInfoFromPrefrence();
        }
        return mUserInfo;
    }

    /**
     * sava userInfo to preference
     *
     * @param userInfo
     */
    private void saveUserInfoToPrefrence(UserInfoData userInfo) {
        SharedPreferences sharedPreferences = getSharedPreferences(Preferences.USERINFO, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (userInfo == null) {
            editor.putString(Preferences.USERINFO, "");
        } else {
            try {
                Gson gson = new Gson();
                String infoJson = gson.toJson(userInfo);
                editor.putString(Preferences.USERINFO, infoJson);
            } catch (Exception e) {
                LogDebug.e(e);
            }
        }
        editor.commit();
    }

    /**
     * get userInfo from preference
     *
     * @return
     */
    private UserInfoData getUserInfoFromPrefrence() {
        SharedPreferences sharedPreferences = getSharedPreferences(Preferences.USERINFO, MODE_PRIVATE);
        String infoJson = sharedPreferences.getString(Preferences.USERINFO, "");
        try {
            Gson gson = new Gson();
            TypeToken<UserInfoData> userInfoTypeToken = new TypeToken<UserInfoData>() {
            };
            Type type = userInfoTypeToken.getType();
            return gson.fromJson(infoJson, type);
        } catch (Exception e) {
            LogDebug.e(e);
            return null;
        }
    }

    /**
     * 创建activity栈
     */
    private void newActivityStack() {
        if (mActivitys == null) {
            mActivitys = new Stack<Activity>();
        }
    }

    /**
     * 添加一个activity
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (!mActivitys.contains(activity)) {
            mActivitys.add(activity);
        }
    }

    /**
     * 获取activity栈
     *
     * @return
     */
    public Stack<Activity> getActivityStack() {
        return mActivitys;
    }

    /**
     * 结束栈顶activity
     */
    public void finishTop() {
        if (!mActivitys.isEmpty()) {
            mActivitys.pop().finish();
        }
    }

    /**
     * 移除一个activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (mActivitys.contains(activity)) {
            mActivitys.remove(activity);
        }
    }


    public static void sendMessage(Message msg) {
        handler.sendMessage(msg);
    }


//    private class MyDaemonListener implements DaemonConfigurations.DaemonListener {
//        @Override
//        public void onPersistentStart(Context context) {
//        }
//
//        @Override
//        public void onDaemonAssistantStart(Context context) {
//        }
//
//        @Override
//        public void onWatchDaemonDaed() {
//        }
//    }


    @SuppressLint("HandlerLeak")
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (mainActivity != null) {
                        mainActivity.sendNotification((String) msg.obj);
                    }
//                  if (payCodeActivity != null) {
//                        payCodeActivity.finishPayCodeActivity();
//                  }
                    break;
                case 1:
                    if (mainActivity != null) {
                        mainActivity.sendCliendId((String) msg.obj);
                    }
                    break;
            }
        }
    }

}
